﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CCWin;
using GroupChat2013.Entity;
using GroupChat2013.Service;
using GroupChat2013.Logic;
using CCWin.SkinControl;
using GroupChat2013.Common;

namespace GroupChat2013.Main
{
    public partial class FrmGroupUserManager : CCSkinMain
    {

        private GroupInfo groupInfo;

        public FrmGroupUserManager(GroupInfo groupInfo)
        {
            InitializeComponent();
            
            ChatListItem ListItem = new ChatListItem("群成员");
            ListItem.IsOpen = true;
            ListItem.IsTwinkleHide = true;
            groupShow.Items.Add(ListItem);

            this.groupInfo = groupInfo;
            lbGroupName.Text = groupInfo.groupName;

            this.Load += new EventHandler(FrmGroupUserManager_Load);

        }

        void FrmGroupUserManager_Load(object sender, EventArgs e)
        {
            //点击树节点动态加载数据
            ChatShow.ClickTreeNode += (s, ex) => { ClickTreeNode(ex.CliceOnTreeItem); };

            InitStructure();

            UpdateUserListInfo();
        }

        /// <summary>
        /// 初始化组织架构
        /// </summary>
        private void InitStructure()
        {
            OrganizeInfo organizeInfo = ServiceUrlProxy.GetInstance().GetOrganizeRootNode(EngineContext.Current.CurrUserInfo.CID);
            if (organizeInfo != null && organizeInfo.deptNodes != null && organizeInfo.deptNodes.Count > 0)
            {
                foreach (OrganizeNode node in organizeInfo.deptNodes)
                {
                    ChatTreeItem root = new ChatTreeItem(node.dept.deptName);
                    root.Data = node;
                    root.IsOpen = true;
                    ChatShow.Items.Add(root);

                    root.IsRequestOK = true;
                    root.IsRequesting = false;
                    ClickTreeNode(root);
                }
            }
        }

        private void ClickTreeNode(ChatTreeItem item)
        {
            item.IsRequesting = true;
            OrganizeNode note = item.Data as OrganizeNode;
            if (note == null) return;

            bool error = false;
            AsyncClient.AsyncCall<OrganizeInfo>(() =>
            {
                return ServiceUrlProxy.GetInstance().GetOrganizeChildNode(note.subDeptNodeUrl, out error);
            },
            (organizeInfo) =>
            {
                if (organizeInfo == null)
                {
                    item.IsRequesting = false;
                }
                else
                {
                    item.IsRequestOK = true;

                    if (organizeInfo.deptNodes != null || organizeInfo.deptNodes.Count > 0)
                    {
                        foreach (OrganizeNode node in organizeInfo.deptNodes)
                        {
                            ChatTreeItem root = new ChatTreeItem(node.dept.deptName);
                            root.Data = node;
                            root.IsOpen = false;
                            item.Items.Add(root);
                        }
                    }

                    if (note.level > 1 && organizeInfo.users != null && organizeInfo.users.Count > 0)
                    {
                        foreach (OrganizeUser user in organizeInfo.users)
                        {
                            ChatTreeSubItem subItem = new ChatTreeSubItem();
                            subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\1.png"));

                            subItem.ID = user.userInfoId;
                            subItem.DisplayName = user.loginName;
                            subItem.NicName = user.name;
                            subItem.ChatType = ChatType.User;
                            subItem.Status = ChatTreeSubItem.UserStatus.Online;
                            item.SubItems.AddAccordingToStatus(subItem);
                        }
                    }
                }
            });
        }

        /// <summary>
        /// 更新群用户列表
        /// </summary>
        private void UpdateUserListInfo()
        {
            try
            {
                AsyncClient.AsyncCall<List<FriendInfo>>(() =>
                {
                    groupShow.Items[0].SubItems.Clear();
                    return ServiceUrlProxy.GetInstance().GetGroupUserList(groupInfo.groupId, EngineContext.Current.CurrUserInfo.CID);
                },
                (friendList) =>
                {
                    if (friendList != null && friendList.Count > 0)
                    {
                        friendList.ForEach(x =>
                        {
                            ChatListSubItem subItem = new ChatListSubItem(x.userInfoId, x.loginName, x.loginName, "", ChatType.User);
                            subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\1.png"));
                            subItem.Status = ChatListSubItem.UserStatus.Online;
                            groupShow.Items[0].SubItems.AddAccordingToStatus(subItem);
                        });
                    }
                });
            }
            catch { }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (groupShow.SelectSubItem != null)
            {
                if (EngineContext.Current.CurrUserInfo.UserId == groupShow.SelectSubItem.ID)
                {
                    MessageBoxEx.Show("自己不能移除自己", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                groupShow.Items[0].SubItems.Remove(groupShow.SelectSubItem);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ChatShow.SelectSubItem != null)
            {
                ChatTreeSubItem treeItem = ChatShow.SelectSubItem;

                bool isExist = false;
                foreach (ChatListSubItem item in groupShow.Items[0].SubItems)
                {
                    if (item.ID == treeItem.ID)
                    {
                        isExist = true;
                        return;
                    }
                }

                if (isExist) return;

                ChatListSubItem listItem = new ChatListSubItem(
                             treeItem.ID,
                             treeItem.NicName,
                             treeItem.DisplayName,
                             treeItem.PersonalMsg,
                             ChatListSubItem.UserStatus.Online,
                             treeItem.ChatType,
                             (Bitmap)treeItem.HeadImage);

                groupShow.Items[0].SubItems.Add(listItem);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string userids = string.Empty;
            
            foreach (ChatListSubItem item in groupShow.Items[0].SubItems)
            {
                userids += string.Format("&userId={0}", item.ID);
            }
            
            try
            {
                AsyncClient.AsyncCall<bool>(() =>
                {
                    return ServiceUrlProxy.GetInstance().AddGroupUser(groupInfo.groupId,
                            EngineContext.Current.CurrUserInfo.CID, userids);
                },
                (succ) =>
                {
                    if (succ)
                    {
                        MessageBoxEx.Show("添加群用户成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        this.Close();
                    }
                    else
                    {
                        MessageBoxEx.Show("添加群用户失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                });
            }
            catch (Exception ex)
            {
                LogHelper.LogError(string.Format("AddGroupUser()方法 错误信息：{0} 堆栈信息：{1} ", ex.Message, ex.StackTrace));
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
